package xyz.ibenben.zhongdian.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.entity.HouseStatus;
import xyz.ibenben.zhongdian.system.entity.OtherRightDigest;
import xyz.ibenben.zhongdian.system.entity.PropertyOwnershipCertificate;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.PropertyOwnershipCertificateForm;
import xyz.ibenben.zhongdian.system.service.HouseStatusService;
import xyz.ibenben.zhongdian.system.service.OtherRightDigestService;
import xyz.ibenben.zhongdian.system.service.PropertyOwnershipCertificateService;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 房产证控制类
 * 提供了一些基本的服务，如初始化、获取房产证列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Controller
@SessionAttributes("propertyOwnershipCertificateForm")
@RequestMapping("/propertyOwnershipCertificate")
public class PropertyOwnershipCertificateController extends BaseController {
    /**
     * 实体名称
     */
    private static final String ENTITYNAME = "propertyOwnershipCertificate";

    @Resource
    private PropertyOwnershipCertificateService propertyOwnershipCertificateService;
    @Resource
    private HouseStatusService houseStatusService;
    @Resource
    private OtherRightDigestService otherRightDigestService;

    /**
     * 数据转换
     *
     * @param binder 转换器
     */
    @InitBinder
    public void binder(WebDataBinder binder) {
        //转换日期
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // CustomDateEditor为自定义日期编辑器
        binder.registerCustomEditor(Date.class, "yearLimitStart", new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Date.class, "yearLimitEnd", new CustomDateEditor(dateFormat, true));
        binder.registerCustomEditor(Date.class, "getCardDate", new CustomDateEditor(dateFormat, true));
    }

    /**
     * 初始化
     *
     * @param map                              参数
     * @param propertyOwnershipCertificateForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, @ModelAttribute PropertyOwnershipCertificateForm propertyOwnershipCertificateForm,
                     HttpSession session) {
        PropertyOwnershipCertificateForm newPropertyOwnershipCertificateForm = new PropertyOwnershipCertificateForm();
        if (propertyOwnershipCertificateForm != null) {
            newPropertyOwnershipCertificateForm = propertyOwnershipCertificateForm;
        }
        SysUser user = (SysUser) session.getAttribute(Constants.SESSION);
        if (user != null && user.getSysRole() != null) {
            newPropertyOwnershipCertificateForm.setCompanyId(user.getSysRole().getCompanyId());
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newPropertyOwnershipCertificateForm);
    }

    /**
     * 获取房产证列表
     *
     * @param map                              参数
     * @param propertyOwnershipCertificateForm 条件参数
     * @return 页面
     */
    @RequestMapping(value = "/getAll")
    @SystemControllerLog(description = "获取房产证列表")
    public String getAll(Model map, @ModelAttribute PropertyOwnershipCertificateForm propertyOwnershipCertificateForm) {
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), propertyOwnershipCertificateForm);
        Page<PropertyOwnershipCertificate> page = new Page<>(propertyOwnershipCertificateForm.getPageIndex(),
                propertyOwnershipCertificateForm.getPageSize());
        IPage<PropertyOwnershipCertificate> result = propertyOwnershipCertificateService.
                findAll(page, propertyOwnershipCertificateForm);
        map.addAttribute(Constants.PI, result);
        return String.format(Constants.LISTPAGE, ENTITYNAME);
    }

    /**
     * 删除房产证记录
     *
     * @param id 房产证主键
     * @return 页面
     */
    @RequestMapping(value = "/delete")
    @SystemControllerLog(description = "删除房产证记录")
    public String delete(@RequestParam("id") Long id, SessionStatus status) {
        propertyOwnershipCertificateService.removeById(id);
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 删除房产证列表
     *
     * @param propertyOwnershipCertificateForm 条件参数
     * @return 页面
     */
    @RequestMapping("/deleteAll")
    @SystemControllerLog(description = "删除房产证列表")
    public String deleteAll(@ModelAttribute PropertyOwnershipCertificateForm propertyOwnershipCertificateForm,
                            SessionStatus status) {
        if (propertyOwnershipCertificateForm.getSelectIds() != null) {
            String[] ids = propertyOwnershipCertificateForm.getSelectIds().split(Constants.COMMA);
            for (String id : ids) {
                propertyOwnershipCertificateService.removeById(Long.parseLong(id));
            }
        }
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 打开房产证添加页面
     *
     * @param map 参数
     * @param id  房屋主键
     * @return 页面
     */
    @GetMapping("/add")
    @SystemControllerLog(description = "打开房产证添加页面")
    public String openAddPage(Model map, @RequestParam("id") Long id) {
        PropertyOwnershipCertificate propertyOwnershipCertificate = new PropertyOwnershipCertificate();
        propertyOwnershipCertificate.setId(id);
        map.addAttribute(ENTITYNAME, propertyOwnershipCertificate);
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 保存房产证添加记录
     *
     * @param propertyOwnershipCertificate 实体
     * @param bindingResult                校验
     * @return 页面
     */
    @PostMapping("/add")
    @SystemControllerLog(description = "保存房产证添加记录")
    public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) PropertyOwnershipCertificate propertyOwnershipCertificate,
                                 BindingResult bindingResult, SessionStatus status) {
        if (!bindingResult.hasErrors()) {
            propertyOwnershipCertificateService.save(propertyOwnershipCertificate);
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        }
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 打开房产证修改页面
     *
     * @param map 参数
     * @param id  房产证主键
     * @return 页面
     */
    @GetMapping("/edit")
    @SystemControllerLog(description = "打开房产证修改页面")
    public String openEditPage(Model map, @RequestParam("id") Long id) {
        map.addAttribute(ENTITYNAME, propertyOwnershipCertificateService.getById(id));
        return String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 更新房产证修改记录
     *
     * @param propertyOwnershipCertificate 实体
     * @param bindingResult                校验
     * @return 页面
     */
    @PostMapping("/edit")
    @SystemControllerLog(description = "更新房产证修改记录")
    public String postEditMessage(@Valid @ModelAttribute(ENTITYNAME) PropertyOwnershipCertificate propertyOwnershipCertificate,
                                  BindingResult bindingResult, SessionStatus status) {
        if (!bindingResult.hasErrors()) {
            propertyOwnershipCertificateService.updateById(propertyOwnershipCertificate);
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        }
        return String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 浏览房产证记录
     *
     * @param map                              参数
     * @param id                               房产证主键
     * @param propertyOwnershipCertificateForm 条件参数
     * @return 页面
     */
    @GetMapping("/view")
    @SystemControllerLog(description = "浏览房产证记录")
    public String openViewPage(Model map, @RequestParam("id") Long id,
                               @ModelAttribute PropertyOwnershipCertificateForm propertyOwnershipCertificateForm) {
        PropertyOwnershipCertificate info = propertyOwnershipCertificateService.getById(id);
        map.addAttribute(ENTITYNAME, info);
        List<HouseStatus> statusList = houseStatusService.findByOwnerId(info.getId());
        map.addAttribute("statusList", statusList);
        List<OtherRightDigest> digestList = otherRightDigestService.findByOwnerId(info.getId());
        map.addAttribute("digestList", digestList);
        return String.format(Constants.VIEWPAGE, ENTITYNAME);
    }

    /**
     * 打开为房屋设置地理坐标位置
     *
     * @param id 房屋主键
     */
    @RequestMapping("/setOwnerShip")
    @SystemControllerLog(description = "打开为房屋设置房产证页面")
    public String setOwnerShip(@RequestParam("id") Long id) {
        PropertyOwnershipCertificate info = propertyOwnershipCertificateService.getById(id);
        if (info == null) {
            return "redirect:/propertyOwnershipCertificate/add?id=" + id;
        } else {
            return "redirect:/propertyOwnershipCertificate/edit?id=" + id;
        }
    }

}

